package com.example.weather;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

import javax.security.auth.login.LoginException;

import static android.view.View.inflate;

public class AddCity extends Activity
{
	int req_id;
	ArrayList<MyCity> cities_tier_list;
	String req_cities_list_net_add;
	String req_cities_list_net_add_old;
	MyListViewAdapter_for_cityies myListViewAdapter_for_cityies;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_view_1);
		//获取起调码，决定显示层数？
		//该页面包含递归
		//一共三层 起调码分别为123，0号为打开页面的起调函数
		//返回码3表示成功拼接请求连接
		//返回码-1表示不想选了要推出选城市页面
		/*
		国内
		https://weather.cma.cn/api/dict/province
			市：北京（ABJ）
			https://weather.cma.cn/api/dict/province/ABJ
				区：北辰
				https://weather.cma.cn/web/weather/54528.html

		国外
		https://weather.cma.cn/api/dict/country
			国：东帝汶
			https://weather.cma.cn/api/dict/country/C115
				城市：帝力
				https://weather.cma.cn/web/weather/097390.html
		 */

		cities_tier_list = new ArrayList<>();
		Intent intent = getIntent();
		req_id = intent.getIntExtra("req_id", -1);
		if (req_id == -1)
		{
			Log.e("TAG", "onCreate 1 req_id error: ");
		}
		switch (req_id)//这里选择显示什么
		{
			case 0:
				//选项只有两个，国内或者国外
				cities_tier_list.add(new MyCity("国内", "province"));
				cities_tier_list.add(new MyCity("国外", "country"));
				break;
			case 1:
			case 2:
				req_cities_list_net_add = intent.getStringExtra("req_netadd");
				Log.e("TAG", "onCreate req_cities_list_net_add: " + req_cities_list_net_add);
				new MyHttp().send_Get_String(req_cities_list_net_add, handler_get, -1);
				break;
		}
		req_cities_list_net_add_old = req_cities_list_net_add;
		ListView listview = findViewById(R.id.Listview_cities_list);
		this.myListViewAdapter_for_cityies = new MyListViewAdapter_for_cityies(getApplicationContext());
		listview.setAdapter(myListViewAdapter_for_cityies);
		listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				Log.e("TAG", "onItemClick 被点击了 : " + position + "   " + req_id);
				Intent intent;
				switch (req_id)//这里选择下个页面显示什么
				{
					//req_id是当前层id，传给下一层的id要加一，将请求连接拼接好之后传给下个页面并启动
					case 0:
						//选项只有两个，国内或者国外
						req_cities_list_net_add = "https://weather.cma.cn/api/dict/" + cities_tier_list.get(position).number;
						Log.e("TAG", "onItemClick 0 req_cities_list_net_add: " + req_cities_list_net_add);
						intent = new Intent(AddCity.this, AddCity.class);
						intent.putExtra("req_id", (int) (req_id + 1));
						intent.putExtra("req_netadd", req_cities_list_net_add);
						startActivityForResult(intent, req_id);//打开添加城市页面
						break;
					case 1:
						req_cities_list_net_add = req_cities_list_net_add_old + '/' + cities_tier_list.get(position).number;
						Log.e("TAG", "onItemClick 0 req_cities_list_net_add: " + req_cities_list_net_add);
						intent = new Intent(AddCity.this, AddCity.class);
						intent.putExtra("req_id", (int) (req_id + 1));
						intent.putExtra("req_netadd", req_cities_list_net_add);
						startActivityForResult(intent, req_id);//打开添加城市页面
						//第二层，接着第一层的链接请求
						break;
					case 2:
						req_cities_list_net_add = "https://weather.cma.cn/web/weather/" + cities_tier_list.get(position).number + ".html";
						Log.e("TAG", "onItemClick 0 req_cities_list_net_add: " + req_cities_list_net_add);
						intent = new Intent();
						//intent.putExtra("req_netadd",req_cities_list_net_add);
						intent.putExtra("city_name", cities_tier_list.get(position).name);
						intent.putExtra("city_number", cities_tier_list.get(position).number);
						//intent.putExtra("req_netadd",req_cities_list_net_add);
						setResult(req_id + 1, intent);//返回码3表示成功拼接请求连接
						finish();
						break;
				}
			}
		});

	}


	@SuppressLint("HandlerLeak")
	final Handler handler_get = new Handler()
	{
		@Override
		public void handleMessage(@NonNull Message msg)
		{
			String str1 = String.valueOf(msg.obj);
			Log.e("TAG", "handleMessage: " + str1);
			String str_list[];
			if (req_id == 1 || req_id == 2)
			{
				str1 = str1.replace("{\"msg\":\"success\",\"code\":0,\"data\":\"", "");
				str1 = str1.replace("\"}", "");
				//Log.e("TAG", "handleMessage: "+str1);
				for (String str2 : str1.split("\\|"))
				{
					//Log.e("TAG", "handleMessage	1: " + str2);
					if (str2 == null || str2.equals(""))
					{
						continue;
					}
					str_list = str2.split(",");
					if (str_list.length < 2) continue;
					cities_tier_list.add(new MyCity(str_list[1], str_list[0]));
				}
				myListViewAdapter_for_cityies.notifyDataSetChanged();
			}
			else
			{
				Toast.makeText(getApplicationContext(), "请求信息/网络异常", Toast.LENGTH_SHORT).show();
			}

		}
	};


	//监听其他页面的返回函数


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		//super.onActivityResult(requestCode, resultCode, data);
		Log.e("TAG", "onActivityResult: " + requestCode + "   " + resultCode);

		if (resultCode == 3)
		{
			setResult(3, data);
			finish();
		}
		else
		{
			setResult(-1);
			finish();
		}
	}

	//退出 和 上一级 两个按钮的处理函数
	public void button_quit(View view)
	{
		setResult(-1);
		finish();
	}

	public void button_last(View view)
	{
		finish();
	}


	class MyListViewAdapter_for_cityies extends BaseAdapter
	{

		Context context;

		public MyListViewAdapter_for_cityies(Context context)
		{
			this.context = context;
		}

		@Override
		public int getCount()
		{
			return cities_tier_list.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position;
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View view = inflate(this.context, R.layout.list_item_text, null);
			TextView textview = view.findViewById(R.id.my_city_text);
			textview.setText(cities_tier_list.get(position).name);
			return view;
		}
	}


}
